package cn.t12.qg.userconsumer.service;

import cn.t12.qg.service.user.UserService;
import cn.t12.qg.userconsumer.exception.UserException;
import cn.t12.qg.userconsumer.vo.TokenVo;
import com.alibaba.fastjson.JSON;
import com.qg.common.Constants;
import com.qg.exception.CommonException;
import com.qg.pojo.QgUser;
import com.qg.utils.RedisUtil;
import com.qg.utils.TokenUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class LocalUserServiceImpl implements LocalUserService {

    @DubboReference(version = "1.0.0")
    private UserService userService;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public TokenVo login(String phone, String password) {
        QgUser loginUser = userService.login(phone,password);
        if(loginUser == null){
            throw new UserException(CommonException.USER_INVALID);
        }
        // 保存到 redis 中
        String token = TokenUtils.createToken(Constants.tokenPrefix,loginUser.getPhone());
        redisUtil.setStr(Constants.tokenPrefix+token, JSON.toJSONString(loginUser), Constants.loginExpire );
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(token);
        return tokenVo;
    }

    @Override
    public void logout(String token) {
        // 清除redis的信息
        redisUtil.del(token);
    }

    @Override
    public boolean exists(String openId) {
        return userService.exists(openId);
    }

    @Override
    public void register(QgUser qgUser) {
        qgUser.setCreatedTime(new Date());
        userService.register(qgUser);
    }

    @Override
    public TokenVo loginByOpenId(String openId) {
        QgUser loginUser = userService.loginByOpenId(openId);
        if(loginUser == null){
            throw new UserException(CommonException.USER_INVALID);
        }
        // 保存到 redis 中
        String token = TokenUtils.createToken(Constants.tokenPrefix,loginUser.getId());
        redisUtil.setStr(Constants.tokenPrefix+token, JSON.toJSONString(loginUser), Constants.loginExpire );
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(token);
        return tokenVo;
    }
}
